import { Modal, Row, Col, Spin, Divider, Dropdown, Form, Icon, Menu, message, Avatar, PageHeader, Popover, Tooltip, } from 'antd';
import React, { useState, useEffect, useContext, useRef } from 'react';
import styles from "./index.less";
import { COL_SPAN } from "@/generic/ConfigParams";
import fileImg from "../imgs/othe.png";
import dirImg from "../imgs/folder.png";
import { dateSort as dataTypeOrder } from "@/generic/Utils";
import { TableListContext } from "../index";
import { downloadMenu, handleUpdate } from "./DirsTable";
import UpdateForm from './UpdateForm';
import { deleteOpt } from "./OptionsHeader";
import { downloadApiRule } from '../service';
import Button from 'antd/es/button/button';


const AllGridItem = props => {

    const { dataArr, vdiskName, onGridItem, rightOpts, tableRefresh, setPreviewVisible, setImg, setRecord } = props;
    const [gridItems, setGridItems ] = useState([]);
    const cols = [];

    const imgThumbnail = async (setImgPath, record) => {
        const response = await downloadApiRule({}, vdiskName, record.path)
        // console.log('==>> response', response)
        if (response.ok) {
            const fileBlob = await response.blob();
            const reader = new FileReader();
            reader.readAsDataURL(fileBlob);
            reader.onload = e => setImgPath(e.target.result);
        }
    }

    const onColClick = (event, record) => {
        console.log("==+>> onColClick", record.isDir)
        if (record.isDir) {
            event.onClick();
            return;
        }
        // props.history.push("/file/detail", {
        //     file: record,
        //     vdiskName,
        // })
        imgThumbnail(setImg, record);
        setRecord(record);
        setPreviewVisible(true);
    }

    const createOptsRow = (record) => {

        return (record.isDir&&
            <>
                <Row><Icon type="edit" onClick={(e) => {
                    rightOpts.setSrcfile(record);
                    rightOpts.setModalVisible(true);
                }} /></Row>
                <Divider type="horizontal" className={styles.divider} />
                <Row><Icon type="delete" style={{ color: "red" }} onClick={() => deleteOpt([record], vdiskName, tableRefresh)} /></Row>
            </>
        );
    }

    useEffect(()=> {
        if (dataArr.length > 0) {
            dataArr.sort(dataTypeOrder);
            dataArr.forEach((item, i) => {
                const event = onGridItem(item);

                const GridItem = props => {

                    const fileRef = useRef();
                    const [showOpts, setShowOpts] = useState(false);
                    const [imgPath, setImgPath] = useState();
                    useEffect(()=> {
                        !item.isDir && imgThumbnail(setImgPath, item);
                    }, [])

                    return (
                        <Col  {...COL_SPAN}
                            onMouseEnter={() => setShowOpts(true)}
                            onMouseLeave={() => setShowOpts(false)}
                        >
                            <div className={styles.colBlock}>
                                <Row>
                                    {
                                        item.isDir 
                                        ? <Col span={!showOpts ? 24 : 18} onClick={() => onColClick(event, item)}>
                                            <Avatar src={dirImg} shape="square" size={64} alt="目录" />
                                        </Col>
                                        : <Col onClick={() => onColClick(event, item)}>
                                            <div style={{height: '64px', paddingTop: '6px'}}>
                                                    <img 
                                                        src={imgPath} alt="预览" 
                                                    />
                                            </div>
                                        </Col>
                                    }
                                    
                                    {
                                        showOpts
                                            ? <Col className={styles.optsBlock}>{createOptsRow(item)}</Col>
                                            : ""
                                    }
                                </Row>
                                <Row>
                                    <div ref={fileRef}>{item.name}</div>
                                </Row>
                            </div>
                        </Col>
                    );
                }

                cols.push(<GridItem key={i} />);
            })

            setGridItems(cols);
        }
        else {
            setGridItems([]);
        }
    }, [dataArr])
    
    return <Row gutter={[16, 16]}>{gridItems}</Row>;
}

const GirdDirsTable = props => {

    const { data, vdisk, currentPath, tableRefresh, rightOpts, } = props;
    const contextOpts = useContext(TableListContext);

    const [gridItems, setGridItems] = useState([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [srcfile, setSrcfile] = useState();
    const [previewVisible, setPreviewVisible] = useState(false);
    const [img, setImg] = useState();
    const [record, setRecord] = useState();

    const modalFooter = (vdiskName = vdisk()) =>{
        return (
            <>
                <Button
                    onClick={(e) => {
                        props.history.push("/file/detail", {
                            file: record,
                            vdiskName,
                        })
                    }}
                ><Icon type='edit' style={{ color: 'blue' }} />编辑</Button>
                {
                    record && 
                    <Dropdown overlay={downloadMenu(record, vdiskName)} placement="bottomLeft" trigger={['click']}>
                        <Button>
                            <Icon type='download' style={{ color: 'green' }} />下载
                        </Button>
                    </Dropdown>
                }
                <Button onClick={() => {
                        deleteOpt([record], vdiskName, tableRefresh);
                        setPreviewVisible(false);
                    }}
                >
                    <Icon type='delete' style={{ color: 'red' }} />删除
                </Button>
            </>
        );
    } 

    useEffect(() => {
        data.then(content => {
            setGridItems(content);
            contextOpts.loading.dispatch({ type: 'loading', value: false })
        })
    }, [data])

    return (
        <div style={{backgroundColor: "#fff"}}>
            <Spin spinning={contextOpts.loading.param} delay={200}>
                <AllGridItem
                    dataArr={gridItems}
                    rightOpts={{ setModalVisible, setSrcfile }}
                    vdiskName={vdisk()}
                    setPreviewVisible={setPreviewVisible}
                    setImg={setImg}
                    setRecord={setRecord}
                    {...props}
                />
            </Spin>
            <UpdateForm
                onSubmit={async value => {

                    const success = await handleUpdate(value, vdisk(), currentPath, srcfile);
                    if (success) {
                        setModalVisible(false);
                        tableRefresh();
                    }
                }}
                onCancel={() => setModalVisible(false)}
                modalVisible={modalVisible}
                srcfile={srcfile}
            />
            <Modal visible={previewVisible} footer={modalFooter()} onCancel={() => setPreviewVisible(false)}>
                <img alt="example" style={{ width: '100%' }} src={img} />
            </Modal>
        </div>
    );
}

export default GirdDirsTable;